<template>
  <div>
    <div v-for="(item,index) in imgArray" :key="index" class="card">
      <div class="card_box">
        <el-image
          :src=" item.url"
          style="width: 148px; height: 148px;display: block;"
          fit="cover"
          v-if="RegExp('.(' + imgType.join('|') + ')$', 'i').test(item.name.toLowerCase())"
          lazy
        ></el-image>
        <video style="width: 148px; height: 148px;display: block;" :src="item.url" v-else></video>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-check"></i>
        </label>
        <!-- 遮罩层icon -->
        <div class="MaskLayer">
          <i class="el-icon-zoom-in" @click="handlePictureCardPreview(item,index)"></i>
          <i class="el-icon-download" @click="downloadImgByBlob(item.url)"></i>
          <i class="el-icon-delete" @click="beforeRemove(item)" v-if="disabled"></i>
        </div>
      </div>
      <div
        class="img_name"
        v-if="imageData.isName"
        :title="(item.size?'['+item.size +']':'' )+ item.name"
      >
        <template v-if="item.size">[{{item.size}}]</template>
        {{item.name}}
      </div>
    </div>
    <div class="card_box" v-if="switchProgress">
      <el-progress type="circle" :percentage="progress"></el-progress>
    </div>
    <el-upload
      v-if="disabled"
      class="upload"
      :action="GLOBAL.urlRoot+ GLOBAL.oaVisionDemand +'/visionDemandUpload/uploadFiles'"
      list-type="picture-card"
      :on-remove="handleRemove"
      :http-request="httpRequest"
      :data="imageData"
      :on-error="uploadError"
      :on-change="handleChange"
      :show-file-list="false"
      multiple
      :on-progress="uploadOnProgress"
      accept=".mp4, .avi, .mov, .wmv, .asf, .navi, .3gp, .mkv, .f4v, .rmvb, .webm, .jpg, .png"
    >
      <i class="el-icon-camera-solid"></i>
    </el-upload>
    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="imgArrayViewer" />
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogImageUrl.name"
      v-if="dialogImageUrl.name"
    >
      <video
        :src="dialogImageUrl.url"
        autoplay="autoplay"
        controls="controls"
        width="100%"
        style="max-height:500px"
      ></video>
    </el-dialog>
  </div>
</template>
<script>
const ERR_OK = 200;
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  components: {
    ElImageViewer,
  },
  props: {
    imageData: Object,
    item: Object,
    disabled: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      showViewer: false,
      imgType: ["jpg", "png", "gif"],
      imgArray: [],
      imgArrayViewer: [],
      dialogImageUrl: "",
      dialogVisible: false,
      progress: 100,
      switchProgress: false,
    };
  },
  created() {
    if(this.item[this.imageData.typeId]){
      this.imgArray = JSON.parse(this.item[this.imageData.typeId]);
    }
  },
  methods: {
    uploadOnProgress(event, file, fileList) {
      this.imageData.findName = file.name;
      this.progress = Math.floor(event.percent);
    },
    httpRequest(params) {
      const file = params.file;
      const form = new FormData();
      // 文件对象
      form.append("file", file);
      form.append("pathType", this.imageData.pathType);
      form.append("typeId", this.imageData.typeId);
      form.append("removeUrl", this.imageData.removeUrl);
      this.progress = 0;
      this.switchProgress = true;
      setTimeout(() => {
        this.progress = Math.floor(95);
        this.$ajax({
          method: "post",
          url: this.GLOBAL.oaVisionDemand + "/visionDemandUpload/uploadFiles",
          data: form,
        }).then((res) => {
          let that = this;
          this.progress = Math.floor(100);
          if (res.data.code === ERR_OK) {
            file.src = res.data.data;
            if (
              RegExp(".(" + this.imgType.join("|") + ")$", "i").test(
                file.name.toLowerCase()
              )
            ) {
              let img = new Image();
              img.src = file.src;
              img.onload = function () {
                that.addImages(file, img);
              };
              img.onerror = function () {
                that.switchProgress = false;
                that.$message.error("图片上传失败，请重新上传");
              };
            } else {
              that.addImages(file);
            }
          } else {
            this.switchProgress = false;
            this.$message.error(res.data.msg);
          }
        });
      }, 10);
    },
    addImages(file, img) {
      this.switchProgress = false;
      this.imgArray.push({
        url: file.src,
        name: file.name,
        size: img ? img.width + "*" + img.height : "",
      });
      this.item[this.imageData.typeId] = JSON.stringify(this.imgArray);
    },
    //删除
    beforeRemove(file) {
      if (this.imageData.removeUrl) {
        return new Promise((resolve, reject) => {
          this.$ajax({
            method: "post",
            url: this.GLOBAL.oaVisionDemand + "/visionDemandUpload/dropFiles",
            params: {
              filePathNames: file.url,
            },
          }).then((res) => {
            if (res.data.code === ERR_OK) {
              this.removeImages(file);
              resolve(true);
            } else {
              reject(false);
              this.$message.error(res.data.msg);
            }
          });
        });
      } else {
        this.removeImages(file);
      }
    },
    removeImages(file) {
      this.$message.success("删除成功");
      this.imgArray.splice(
        this.imgArray.findIndex((item) => item.url === file.url),
        1
      );
      if (this.imgArray.length !== 0) {
        this.item[this.imageData.typeId] = JSON.stringify(this.imgArray);
      } else {
        this.item[this.imageData.typeId] = "[]";
      }
    },
    handleRemove(file, fileList) {},
    uploadError(err, file, fileList) {
      this.updLoading = false;
      this.switchProgress = false;
      this.$message.error("上传出错,请重新上传----" + err);
    },
    handleChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 100MB!");
      }
    },
    handlePictureCardPreview(file, index) {
      if (
        RegExp(".(" + this.imgType.join("|") + ")$", "i").test(
          file.name.toLowerCase()
        )
      ) {
        this.showViewer = true;
        let arr = []; 
        let i = 0;
        for (i; i < this.imgArray.length; i++) {
          if (
            RegExp(".(" + this.imgType.join("|") + ")$", "i").test(
              this.imgArray[i + index].name.toLowerCase()
            )
          ) {
            arr.push(this.imgArray[i + index].url);
          }
          if (i + index >= this.imgArray.length - 1) {
            index = 0 - (i + 1);
          }
        }
        this.imgArrayViewer = arr;
      } else {
        this.dialogImageUrl = file;
        this.dialogVisible = true;
      }
    },
    closeViewer() {
      this.showViewer = false;
    },
    downloadImgByBlob(url) {
      var url = url; // 获取图片地址
      var a = document.createElement("a"); // 创建一个a节点插入的document
      var event = new MouseEvent("click"); // 模拟鼠标click点击事件
      a.download = "beautifulGirl"; // 设置a节点的download属性值
      a.target = "_blank";
      a.href = url; // 将图片的src赋值给a节点的href
      a.dispatchEvent(event);
    },
  },
};
</script>
<style lang="stylus" scoped>
.upload {
  display: inline-block;
  vertical-align: top;
}

.card {
  display: inline-block;
  vertical-align: top;

  .img_name {
    font-size: 14px;
    line-height: 16px;
    padding: 0px;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 148px;
  }
}

.card_box {
  position: relative;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  display: inline-block;
  vertical-align: top;
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  text-align: center;

  .el-progress {
    margin-top: 10px;
  }

  .MaskLayer {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #fff;
    text-align: center;
    z-index: 5;
    opacity: 0;
    transition: all 0.3s;
    background-color: rgba(0, 0, 0, 0.4);

    i {
      font-size: 20px;
      margin: 60px 5px 0 5px;
      cursor: pointer;
    }

    &:hover {
      opacity: 1;
    }
  }
}

.el-upload-list__item-status-label {
  display: block;
  position: absolute;
  right: -15px;
  top: -6px;
  width: 40px;
  height: 24px;
  line-height: 32px;
  background: #13ce66;
  text-align: center;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  -webkit-box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);

  i {
    color: #ffffff;
    font-size: 12px;
    margin-top: 11px;
    transform: rotate(-45deg);
  }
}

.img-li-b--delete {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: #8492a6;
  cursor: pointer;
  font-size: 1.1em;
}
</style> 